package com.wzapp.sitposture.authentication.interceptor;

import com.wzapp.sitposture.common.annotation.NeedLogin;
import com.wzapp.sitposture.common.base.HeaderParam;
import com.wzapp.sitposture.common.base.SpringContextHolder;
import com.wzapp.sitposture.common.util.HeaderUtil;
import com.wzapp.sitposture.usercenter.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NeedLoginInterceptor implements HandlerInterceptor {

	protected static final Logger log = LoggerFactory.getLogger(NeedLoginInterceptor.class);

	private UserService userService = SpringContextHolder.getBean(UserService.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

        HeaderParam headerParam = HeaderUtil.getHeaderParam(request);

		final String token = headerParam.getToken();

		if (handler instanceof HandlerMethod
				&& ((HandlerMethod) handler).getMethod().isAnnotationPresent(NeedLogin.class)) {
//todo
//            if (!HeaderUtil.validToken(token)) {
//                throw new AuthenticationException("authentication.token.error");
//            }

//            if (HeaderUtil.isTokenExpired(token)) {
//                throw new AuthenticationException("authentication.token.expired");
//            }

//            String userId = HeaderUtil.getUserIdFromPrincipal(token);
//            if (ToolUtil.isEmpty(userId)) {
//                throw new AuthenticationException("userCenter.user.not.exists.error");
//            }else{
//				User user = userService.getUserById(userId);
//				if (ToolUtil.isEmpty(user)) {
//					throw new AuthenticationException("userCenter.user.not.exists.error");
//				}
//
//				return true;
//            }

		}

		return true;
	}

}
